<?php defined('BASEPATH') OR exit('No direct script access allowed');


include_once(APPPATH.'libraries/MarketplaceWebService/Client.php');
include_once(APPPATH.'libraries/MarketplaceWebService/Exception.php');
include_once(APPPATH.'libraries/MarketplaceWebService/Model/TypeList.php');
define ('DATE_FORMAT', 'Y-m-d\TH:i:s\Z');
require APPPATH.'/libraries/REST_Controller.php';

class Reports extends REST_Controller
{
    private $service;
    public $request;
    public $next_by_token = FALSE;
    function __construct()
    {
        // Construct our parent class
        parent::__construct();
        
        
        $serviceUrl = '';
        switch ($this->_merchant['region']) 
        {
            case 'NA':
                $serviceUrl = "https://mws.amazonservices.com";
                break;
            
            case 'CA':
                $serviceUrl = "https://mws.amazonservices.ca";
                break;

            case 'DE':
                $serviceUrl = "https://mws.amazonservices.de";
                break;

            case 'FR':
                $serviceUrl = "https://mws.amazonservices.fr";
                break;
            
            case 'IT':
                $serviceUrl = "https://mws.amazonservices.it";
                break;

            case 'UK':
                $serviceUrl = "https://mws.amazonservices.co.uk";
                break;

            case 'JP':
                $serviceUrl = "https://mws.amazonservices.com.cn";
                break;

            case 'CN':
                $serviceUrl = "https://mws.amazonservices.com.cn";
                break;

            default:
                $serviceUrl = "https://mws.amazonservices.com";
                break;
        }

        $this->service = new MarketplaceWebService_Client(
            AWS_ACCESS_KEY_ID,
            AWS_SECRET_ACCESS_KEY,
            array (
                'ServiceURL' => $serviceUrl,
                'ProxyHost' => null,
                'ProxyPort' => -1,
                'MaxErrorRetry' => 3
                ),
            APPLICATION_NAME,
            APPLICATION_VERSION
        );

        $tmp = $this->input->get('next_by_token');
        if($tmp)
        {
			$this->next_by_token = ((int)$tmp)?TRUE:FALSE;
		}
		
			
    }
    
    function requestReport_get()
    {
        //include required libraries
        include_once(APPPATH.'libraries/MarketplaceWebService/Model/RequestReportRequest.php');
        
        //create object of order request
        $this->request = new MarketplaceWebService_Model_RequestReportRequest();

        //set SELLER ID
        $this->request->setMerchant(MERCHANT_ID);
        $marketplaceIdArray = array("Id" => array(MARKETPLACE_ID));
        $this->request->setMarketplaceIdList($marketplaceIdArray);

        $params = array(
                    'ReportType' => array('type' => 'string'),
                    'StartDate' => array('type' => 'date'),
                    'EndDate' => array('type' => 'date'),
                    );
        $this->amazon_mws->set_request( $params, 'get');


        $this->invokeRequestReport($this->service, $this->request);        
        
    }

    function invokeRequestReport(MarketplaceWebService_Interface $service, $request)
    {
        try 
        {
            $response = $service->requestReport($request);
            //echo $response->toXML;exit;
            $this->amazon_mws->format_output($response, 'RequestReportResult', 'RequestReportResult');

            $this->amazon_mws->show_ouput(TRUE);


         } 
        catch (MarketplaceWebService_Exception $ex) 
         {
            $this->amazon_mws->format_error($ex->getXML());
            $this->amazon_mws->show_ouput(FALSE);
         }
    }
    
    
    

    /** GET REPORT REQUEST LIST **/

    
    function reportRequestList_get()
    {
         include_once(APPPATH.'libraries/MarketplaceWebService/Model/GetReportRequestListRequest.php');
         include_once(APPPATH.'libraries/MarketplaceWebService/Model/IdList.php');

         $this->request = new MarketplaceWebService_Model_GetReportRequestListRequest();
         $this->request->setMerchant(MERCHANT_ID);
         $params = array(
                    'MaxCount' => array('type' => 'string'),
                    'ReportTypeList' => array('type' => 'ReportTypeList'),
                    'ReportProcessingStatusList' => array('type' => 'ReportProcessingStatusList'),
                    'ReportRequestIdList' => array('type' => 'ReportRequestIdList')
                    );
         $r = new MarketplaceWebService_Model_IdList();
         if( $this->input->get('ReportRequestIdList') )
            $r->setId($this->input->get('ReportRequestIdList'));

        $this->request->setReportRequestIdList($r);

        $this->amazon_mws->set_request( $params, 'get');
         $this->invokeGetReportRequestList($this->service, $this->request);
         
    }


    function invokeGetReportRequestList(MarketplaceWebService_Interface $service, $request)
    { 
        
        try 
        { 
            $response = $service->getReportRequestList($request);
            $this->amazon_mws->format_output($response, 'GetReportRequestListResult', 'GetReportRequestListResult');
            
            if ($response->isSetGetReportRequestListResult()) 
            {
                $getReportRequestListResult = $response->getGetReportRequestListResult();
                if ($getReportRequestListResult->isSetNextToken()) 
                {
                    $this->amazon_mws->next_token = $getReportRequestListResult->getNextToken();
                }
            }


            $this->amazon_mws->show_ouput(TRUE);

         } 
        catch (MarketplaceWebService_Exception $ex) 
         {
            $this->amazon_mws->format_error($ex->getXML());
            $this->amazon_mws->show_ouput(FALSE);
         }
        
        
    }

    function reportRequestListByNextToken_get()
    {
        include_once(APPPATH.'libraries/MarketplaceWebService/Model/GetReportRequestListByNextTokenRequest.php');
        $this->request = new MarketplaceWebService_Model_GetReportRequestListByNextTokenRequest();
        $this->request->setMerchant(MERCHANT_ID);
        $params = array(
                    'NextToken' => array('type' => 'string')
                    );
        $this->amazon_mws->set_request( $params, 'get');
        
        $this->invokeGetReportRequestListByNextToken($this->service, $this->request);
        
    }


    function invokeGetReportRequestListByNextToken(MarketplaceWebService_Interface $service, $request) 
    {
        try 
        { 
            $response = $service->getReportRequestListByNextToken($request);
            //echo $response->toXML();exit;
            $this->amazon_mws->format_output($response, 'GetReportRequestListResultByNextToken', 'GetReportRequestListResult');
            
            if ($response->isSetGetReportRequestListByNextTokenResult())
            {
                $getReportRequestListByNextTokenResult = $response->getGetReportRequestListByNextTokenResult();
                if ($getReportRequestListByNextTokenResult->isSetNextToken())
                {
                    $this->amazon_mws->next_token = $getReportRequestListByNextTokenResult->getNextToken();
                }
            }

            $this->amazon_mws->show_ouput(TRUE);

         } 
        catch (MarketplaceWebService_Exception $ex) 
         {
            $this->amazon_mws->format_error($ex->getXML());
            $this->amazon_mws->show_ouput(FALSE);
         }
        
    }


    function reportList_get()
    {
         include_once(APPPATH.'libraries/MarketplaceWebService/Model/GetReportListRequest.php');
         
                    
         $this->request = new MarketplaceWebService_Model_GetReportListRequest();
         $this->request->setMerchant(MERCHANT_ID);
         $this->request->setAvailableToDate(new DateTime('now', new DateTimeZone('UTC')));
         $this->request->setAvailableFromDate(new DateTime('-3 months', new DateTimeZone('UTC')));

         $params = array(
                    'MaxCount' => array('type' => 'string'),
                    'ReportTypeList' => array('type' => 'ReportTypeList'),
                    );
         $this->amazon_mws->set_request( $params, 'get');
         
         $afd = $this->input->get('AvailableFromDate');
         if( $afd )
         {
            $this->request->setAvailableFromDate(new DateTime('-'.$afd.' days', new DateTimeZone('UTC')));
         }
         
         
         $this->request->setAcknowledged(false);

         $this->invokeGetReportList($this->service, $this->request);
         
    }

    function reportListByNextToken_get()
    {
        include_once(APPPATH.'libraries/MarketplaceWebService/Model/GetReportListByNextTokenRequest.php');
        $this->request = new MarketplaceWebService_Model_GetReportListByNextTokenRequest();
        $this->request->setMerchant(MERCHANT_ID);
        $params = array(
                    'NextToken' => array('type' => 'string')
                    );
        $this->amazon_mws->set_request( $params, 'get');

        $this->invokeGetReportList($this->service, $this->request, 'next_token');
    }

    function invokeGetReportList(MarketplaceWebService_Interface $service, $request, $type = null)
    { 

        
        try 
        { 
            $getReportList = 'getReportList';
            $isSetGetReportListResult = 'isSetGetReportListResult';
            $getGetReportListResult = 'getGetReportListResult';

            if(strcmp($type, 'next_token') === 0 )
            {
                $getReportList          = "getReportListByNextToken"; 
                $isSetGetReportListResult = 'isSetGetReportListByNextTokenResult';
                $getGetReportListResult = 'getGetReportListByNextTokenResult';
            }

            $response = $service->$getReportList($request);
            //echo $response->toXML();die;
            $this->amazon_mws->format_output($response, ucfirst($getReportList).'Result', 'GetReportListResult');
            
            //Get Next Token to fetch the next records in Queue
            $next_token = '';

            if ($response->$isSetGetReportListResult()) 
            {
                $getReportListResult = $response->$getGetReportListResult();

                if ($getReportListResult->isSetNextToken()) 
                {
                    $next_token = $getReportListResult->getNextToken(); 
                }
                
            }

		   $this->amazon_mws->next_token = $next_token;
		   
           if( strcmp($next_token,'') !== 0 && $this->next_by_token)
            {
                include_once(APPPATH.'libraries/MarketplaceWebService/Model/GetReportListByNextTokenRequest.php');
                $this->request = new MarketplaceWebService_Model_GetReportListByNextTokenRequest();
                $this->request->setMerchant(MERCHANT_ID);
                $this->request->setNextToken($next_token);
                
                $this->invokeGetReportList($this->service, $this->request, 'next_token');
            }
            else
            {
                $this->amazon_mws->show_ouput(TRUE);
            }



         } 
        catch (MarketplaceWebService_Exception $ex) 
         {
            $this->amazon_mws->format_error($ex->getXML());
            $this->amazon_mws->show_ouput(FALSE);
         }
        
        
    }


    function getReportScheduleList_get()
    {
         include_once(APPPATH.'libraries/MarketplaceWebService/Model/GetReportScheduleListRequest.php');
         
         $this->request = new MarketplaceWebService_Model_GetReportScheduleListRequest();
         $this->request->setMerchant(MERCHANT_ID);
         
         $params = array(
                    'MaxCount' => array('type' => 'string')
                    );
        $this->amazon_mws->set_request( $params, 'get');
         $this->invokeGetReportScheduleList($this->service, $this->request);
         
    }


    function invokeGetReportScheduleList(MarketplaceWebService_Interface $service, $request)
    { 
        
        try 
        { 
            $response = $service->getReportScheduleList($request);
            $this->amazon_mws->format_output($response, 'GetReportScheduleListResult', 'GetReportScheduleListResult');
            $this->amazon_mws->show_ouput(TRUE);

         } 
        catch (MarketplaceWebService_Exception $ex) 
         {
            $this->amazon_mws->format_error($ex->getXML());
            $this->amazon_mws->show_ouput(FALSE);
         }
        
        
    }

    /**  GET REPORT  **/
    
        
    function report_get()
    {
        
        
        include_once(APPPATH.'libraries/MarketplaceWebService/Model/GetReportRequest.php');
        
        $this->request = new MarketplaceWebService_Model_GetReportRequest();
        $this->request->setMerchant(MERCHANT_ID);
        $params = array(
                    'ReportId' => array('type' => 'string')
                    );
        $this->amazon_mws->set_request( $params, 'get');
        $filename = $this->amazon_mws->create_file('reports', $this->request->getReportId());
        
        $this->request->setReport(@fopen($filename, 'rw+'));
    
        $this->invokeGetReport($this->service, $this->request);
        
    }


    function invokeGetReport(MarketplaceWebService_Interface $service, $request) 
    {
        
        try 
        { 
            $response = $service->getReport($request);
            $this->amazon_mws->format_output($response, 'GetReportResult', 'GetReportResult');
            $this->amazon_mws->show_ouput(TRUE);

         } 
        catch (MarketplaceWebService_Exception $ex) 
         {
            $this->amazon_mws->format_error($ex->getXML());
            $this->amazon_mws->show_ouput(FALSE);
         }
         
    }
    
    
    /** GET REPORT COUNT **/
    
    
    function reportCount_get()
    {
		
		include_once(APPPATH.'libraries/MarketplaceWebService/Model/GetReportCountRequest.php');
		
		$this->request = new MarketplaceWebService_Model_GetReportCountRequest();
		$this->request->setMerchant(MERCHANT_ID);
		$this->request->setAvailableFromDate(new DateTime('-6 months', new DateTimeZone('UTC')));
		$this->request->setAvailableToDate(new DateTime('now', new DateTimeZone('UTC')));
		
		$this->invokeGetReportCount($this->service, $this->request);
		
	}


	function invokeGetReportCount(MarketplaceWebService_Interface $service, $request)
	{
		
		try 
        { 
            $response = $service->getReportCount($request);
           // echo $response->toXML();exit;
            $this->amazon_mws->format_output($response, 'GetReportCountResult', 'GetReportCountResult');
            $this->amazon_mws->show_ouput(TRUE);

         } 
        catch (MarketplaceWebService_Exception $ex) 
         {
            $this->amazon_mws->format_error($ex->getXML());
            $this->amazon_mws->show_ouput(FALSE);
         }
         
	}
	
	/**  GET REPORT SCHEDULE COUNT **/
	
	
	function reportScheduleCount_get()
	{
		include_once(APPPATH.'libraries/MarketplaceWebService/Model/GetReportScheduleCountRequest.php');
		
		$this->request = new MarketplaceWebService_Model_GetReportScheduleCountRequest();
		$this->request->setMerchant(MERCHANT_ID);
		
		$this->invokeGetReportScheduleCount($this->service, $this->request);
		
	}
	

	function invokeGetReportScheduleCount(MarketplaceWebService_Interface $service, $request)
	{
		
		try 
        { 
            $response = $service->getReportScheduleCount($request);
			//echo $response->toXML();exit;
            $this->amazon_mws->format_output($response, 'GetReportScheduleCountResult', 'GetReportScheduleCountResult');
            $this->amazon_mws->show_ouput(TRUE);

         } 
        catch (MarketplaceWebService_Exception $ex) 
         {
            $this->amazon_mws->format_error($ex->getXML());
            $this->amazon_mws->show_ouput(FALSE);
         }
         
	}
	
	
	/**  GET REPORT REQUEST COUNT  **/
	
	
	function reportRequestCount_get()
	{
		include_once(APPPATH.'libraries/MarketplaceWebService/Model/GetReportRequestCountRequest.php');
		
		$this->request = new MarketplaceWebService_Model_GetReportRequestCountRequest();
		$this->request->setMerchant(MERCHANT_ID);
		
		include_once(APPPATH.'libraries/MarketplaceWebService/Model/StatusList.php');
		$statusList = new MarketplaceWebService_Model_StatusList();
		$this->request->setReportProcessingStatusList($statusList->withStatus('_SUBMITTED_', '_DONE_'));
		
		$this->invokeGetReportRequestCount($this->service, $this->request);
		
	}


	function invokeGetReportRequestCount(MarketplaceWebService_Interface $service, $request)
	{
		try 
        { 
            $response = $service->getReportRequestCount($request);
			//echo $response->toXML();exit;
            $this->amazon_mws->format_output($response, 'GetReportRequestCountResult', 'GetReportRequestCountResult');
            $this->amazon_mws->show_ouput(TRUE);

         } 
        catch (MarketplaceWebService_Exception $ex) 
         {
            $this->amazon_mws->format_error($ex->getXML());
            $this->amazon_mws->show_ouput(FALSE);
         }
		
	}


	/**  MANAGE REPORT SECHEDULE **/
	
	
	function manageReportSchedule_get()
	{
		
		include_once(APPPATH.'libraries/MarketplaceWebService/Model/ManageReportScheduleRequest.php');
		
		$this->request = new MarketplaceWebService_Model_ManageReportScheduleRequest();
		$this->request->setMerchant(MERCHANT_ID);
		$this->request->setReportType('_GET_ORDERS_DATA_');
		$this->request->setSchedule('_1_HOUR_');
		$this->request->setScheduleDate(new DateTime('now', new DateTimeZone('UTC')));
		
		$this->invokeManageReportSchedule($this->service, $this->request);
		
	}


	function invokeManageReportSchedule(MarketplaceWebService_Interface $service, $request) 
	{
		try 
        { 
            $response = $service->manageReportSchedule($request);
			//echo $response->toXML();exit;
            $this->amazon_mws->format_output($response, 'GetReportRequestCountResult', 'GetReportRequestCountResult');
            $this->amazon_mws->show_ouput(TRUE);

         } 
        catch (MarketplaceWebService_Exception $ex) 
         {
            $this->amazon_mws->format_error($ex->getXML());
            $this->amazon_mws->show_ouput(FALSE);
         }
         
	}
	
	
	/** GET UPDATE REPORT ACKNOWLEDGEMENT **/


	function UpdateReportAcknowledgements_get()
	{
		
		include_once(APPPATH.'libraries/MarketplaceWebService/Model/UpdateReportAcknowledgementsRequest.php');
		include_once(APPPATH.'libraries/MarketplaceWebService/Model/IdList.php');
		
		$this->request = new MarketplaceWebService_Model_UpdateReportAcknowledgementsRequest();
		$this->request->setMerchant(MERCHANT_ID);
		$idList = new MarketplaceWebService_Model_IdList();
		$reportId = "23361743003";
		$this->request->setReportIdList($idList->withId($reportId));
		$this->request->setAcknowledged(false);
		
		$this->invokeUpdateReportAcknowledgements($this->service, $this->request);
	
	}


	function invokeUpdateReportAcknowledgements(MarketplaceWebService_Interface $service, $request)
	{
		try 
        { 
            $response = $service->updateReportAcknowledgements($request);
			//echo $response->toXML();exit;
            $this->amazon_mws->format_output($response, 'UpdateReportAcknowledgementsResult', 'UpdateReportAcknowledgementsResult');
            $this->amazon_mws->show_ouput(TRUE);

         } 
        catch (MarketplaceWebService_Exception $ex) 
         {
            $this->amazon_mws->format_error($ex->getXML());
            $this->amazon_mws->show_ouput(FALSE);
         }
		
	}
	
	
	
	/** Report schedule list by next token **/
	
	function reportScheduleListByNextToken_get()
	{
		include_once(APPPATH.'libraries/MarketplaceWebService/Model/GetReportScheduleListByNextTokenRequest.php');
		$this->request = new MarketplaceWebService_Model_GetReportScheduleListByNextTokenRequest();
		
		$this->request->setMerchant(MERCHANT_ID);
		$params = array(
                    'NextToken' => array('type' => 'string')
                    );
        $this->amazon_mws->set_request( $params, 'get');
		$this->invokeGetReportScheduleListByNextToken($this->service, $this->request);

		
	}
	
	function invokeGetReportScheduleListByNextToken(MarketplaceWebService_Interface $service, $request) 
	{
		try 
        { 
            $response = $service->getReportScheduleListByNextToken($request);
			//echo $response->toXML();exit;
            $this->amazon_mws->format_output($response, 'GetReportScheduleListResultByNextToken', 'GetReportScheduleListResultByNextToken');
            $this->amazon_mws->show_ouput(TRUE);

         } 
        catch (MarketplaceWebService_Exception $ex) 
         {
            $this->amazon_mws->format_error($ex->getXML());
            $this->amazon_mws->show_ouput(FALSE);
         }
	}
	
	
      
    
}
